package com.wootion.cims.module.communityresidence.residencelist.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wootion.cims.dao.*;
import com.wootion.cims.general.utils.GetIp;
import com.wootion.cims.module.basicinformation.plotsetting.model.Building;
import com.wootion.cims.module.basicinformation.plotsetting.model.BungalowVilla;
import com.wootion.cims.module.basicinformation.plotsetting.model.PlotMessage;
import com.wootion.cims.module.basicinformation.plotsetting.model.Unit;
import com.wootion.cims.module.communitypersonal.model.Person;
import com.wootion.cims.module.communityresidence.residencelist.dto.ResidencePageQuery;
import com.wootion.cims.module.communityresidence.residencelist.dto.ResidenceDto;
import com.wootion.cims.module.communityresidence.residencelist.dto.Rules;
import com.wootion.cims.module.communityresidence.residencelist.excel.ResidenceExcel;
import com.wootion.cims.module.communityresidence.residencelist.model.Residence;
import com.wootion.cims.module.communityresidence.residencelist.service.ResidenceService;
import com.wootion.cims.module.communityservice.dto.PersonDto;
import com.wootion.cims.module.systemsetting.community.model.SysCommunity;
import com.wootion.cims.module.systemsetting.log.model.SysLog;
import com.wootion.cims.module.systemsetting.polt.model.SysPlot;
import com.wootion.cims.module.systemsetting.user.model.SysUserRole;
import com.wootion.cims.module.systemsetting.user.model.User;
import com.wootion.cims.response.ResponseResult;
import com.wootion.cims.response.ResultCode;
import com.wootion.cims.shiro.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: LanQiang
 * @Date: 2022/12/08/16:05
 * @Description: 作用xxx
 */
@Service
@Slf4j
public class ResidenceServiceImpl implements ResidenceService {
    @Resource
    private ResidenceDao residenceDao;
    @Resource
    private SysUserRoleDao sysUserRoleDao;
    @Resource
    private SysRoleDao sysRoleDao;
    @Resource
    private SysUserCommunityDao sysUserCommunityDao;
    @Resource
    private SysCommunityDao sysCommunityDao;
    @Resource
    private SysPlotDao sysPlotDao;
    @Resource
    private PersonDao personDao;
    @Value("${cims.path}")
    private String basePath;
    @Resource
    private SysLogDao sysLogDao;
    /**
     * 查询社区分组信息
     *
     * @return
     */
    @Override
    public ResponseResult groupByCommunity() {
        User user = (User) ShiroUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper5 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper5.eq(SysUserRole::getUserId, user.getId());
        SysUserRole sysUserRole = sysUserRoleDao.selectOne(lambdaQueryWrapper5);
        String roleKey = sysRoleDao.findByRoles(sysUserRole.getRoleId());
        List<SysCommunity> communities = null;
        if ("street:admin".equals(roleKey)) {
            //List<String> communityIds = residenceDao.communityIds(null,classes,category);
            communities = sysCommunityDao.findByCommunityIds(null);
            return ResponseResult.builder().data(communities).build();
        }else {
            List<String> commnityIds = sysUserCommunityDao.commnityIds(user.getId());
            if (Objects.isNull(commnityIds) || commnityIds.size() <= 0) {
                return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("当前用户还没有任何社区权限").build();
            }
            communities = sysCommunityDao.findByCommunityIds(commnityIds);
        }
        return ResponseResult.builder().data(communities).build();
    }

    /**
     * 根据社区id，查询小区分组信息
     *
     * @return
     */
    @Override
    public ResponseResult groupByPlot(String communityId) {
        List<SysPlot> plotList = sysPlotDao.findPlotList(communityId);
        return ResponseResult.builder().data(plotList).build();
    }

    /**
     * 根据小区id，查询小区的楼栋和单元信息
     *
     * @return
     */
    @Override
    public ResponseResult groupByPlotBuilding(String plotId, String category) {
        LambdaQueryWrapper<SysPlot> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysPlot::getId, plotId);
        lambdaQueryWrapper.eq(SysPlot::getEnabled, true);
        SysPlot sysPlot = sysPlotDao.selectOne(lambdaQueryWrapper);
        if (Objects.isNull(sysPlot)) {
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("关联的小区已经被禁用！").build();
        }
        if ("平房/别墅".equals(category)) {
            if (sysPlot.getBungalowVilla() == null) {
                return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("小区还未添加任何平房/别墅信息").build();
            }
            String bungalowVilla = sysPlot.getBungalowVilla();
            PlotMessage plotMessage = JSON.parseObject(bungalowVilla, PlotMessage.class);
            List<Map<String, Object>> mapList = new ArrayList<>();
            List<BungalowVilla> bungalowVillas = plotMessage.getBungalowVillas();
            for (BungalowVilla villa : bungalowVillas) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", villa.getId());
                map.put("name", villa.getArea());
                mapList.add(map);
            }
            return ResponseResult.builder().data(mapList).build();
        } else {
            if (sysPlot.getBuildingUnit() == null) {
                return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("小区还未添加任何楼栋和单元信息").build();
            }
            String buildingUnit = sysPlot.getBuildingUnit();
            PlotMessage plotMessage = JSON.parseObject(buildingUnit, PlotMessage.class);
            List<Building> buildings = plotMessage.getBuildings();
            List<Map<String, Object>> mapList = new ArrayList<>();
            for (Building building : buildings) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", building.getId());
                map.put("name", building.getStoriedBuilding());
                List<Unit> units = building.getUnits();
                if(!Objects.isNull(units) && units.size()>0){
                    List<Map<String, Object>> maps = new ArrayList<>();
                    for (Unit unit : units) {
                        Map<String, Object> map1 = new HashMap<>();
                        map1.put("id", unit.getId());
                        map1.put("name", unit.getUnit());
                        maps.add(map1);
                    }
                    map.put("children", maps);
                    mapList.add(map);
                }
                //没有关联单元的楼不让他查询出来
//                else{
//                    mapList.add(map);
//                }
            }
            return ResponseResult.builder().data(mapList).build();
        }
    }
    /**
     * 根据小区id和详细地址获取，当前地址下的所有门牌号
     * @param residenceDto
     * @return
     */
    @Override
    public ResponseResult groupByHouseNumber(ResidenceDto residenceDto) {
        String plotId = residenceDto.getPlotId();//小区id
        List<String> addrArray = residenceDto.getAddrArray();
        if(!StringUtils.hasText(plotId)){
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("小区id不可以为空").build();
        }
        if(Objects.isNull(addrArray) || addrArray.size()<=0){
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("小区详细地址不能为空").build();
        }
        LambdaQueryWrapper<SysPlot> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysPlot::getId,plotId);
        lambdaQueryWrapper.eq(SysPlot::getEnabled,true);
        SysPlot sysPlot = sysPlotDao.selectOne(lambdaQueryWrapper);
        //平房/别墅
        if(addrArray.size() == 1){
            String bungalowVilla = sysPlot.getBungalowVilla();
            if(!StringUtils.hasText(bungalowVilla)){
                return ResponseResult.builder().message("当前小区还未添加任何区域地址").build();
            }
            PlotMessage plotMessage = JSON.parseObject(bungalowVilla, PlotMessage.class);
            List<BungalowVilla> bungalowVillas = plotMessage.getBungalowVillas();
            for (BungalowVilla villa : bungalowVillas) {
                if(addrArray.get(0).equals(villa.getId())){
                    String area = villa.getArea();//获取区域信息
                    LambdaQueryWrapper<Residence> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper1.eq(Residence::getPlotId,plotId);
                    lambdaQueryWrapper1.eq(Residence::getEnabled,true);
                    lambdaQueryWrapper1.eq(Residence::getAddress,area);
                    List<Residence> residenceList = residenceDao.selectList(lambdaQueryWrapper1);
                    return ResponseResult.builder().data(residenceList).build();
                }
            }
        }else {
            //楼房
            String buildingUnit = sysPlot.getBuildingUnit();
            if(!StringUtils.hasText(buildingUnit)){
                return ResponseResult.builder().message("当前小区还未添加任何楼栋和单元").build();
            }
            PlotMessage plotMessage = JSON.parseObject(buildingUnit, PlotMessage.class);
            List<Building> buildings = plotMessage.getBuildings();//获取楼栋
            for (Building building : buildings) {
                if(building.getId().equals(addrArray.get(0))){
                    //拿到楼栋名称
                    StringBuilder buildingName = new StringBuilder(building.getStoriedBuilding());
                    List<Unit> units = building.getUnits();
                    if(units != null){
                        for (Unit unit : units) {
                            if(unit.getId().equals(addrArray.get(1))){
                                buildingName.append("/");
                                buildingName.append(unit.getUnit());
                                LambdaQueryWrapper<Residence> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                                lambdaQueryWrapper1.eq(Residence::getPlotId,plotId);
                                lambdaQueryWrapper1.eq(Residence::getEnabled,true);
                                lambdaQueryWrapper1.eq(Residence::getAddress,buildingName.toString());
                                List<Residence> residenceList = residenceDao.selectList(lambdaQueryWrapper1);
                                return ResponseResult.builder().data(residenceList).build();
                            }
                        }
                    }
                }
            }
        }
        return ResponseResult.builder().build();
    }

    /**
     * 查询业主信息
     */
    @Override
    public ResponseResult findByPerson(Integer page, Integer limit, String condition) {
        String condition2 = condition.trim();//去掉前后空格
        PageDTO<PersonDto> pageDTO = new PageDTO<>(page,limit);
        PageDTO<PersonDto> page1 = personDao.findPage(pageDTO, condition2);
        if(!Objects.isNull(page1)){
            List<PersonDto> records = page1.getRecords();
            //处理居住地址和户籍地址
            for (PersonDto record : records) {
                String abodeId = record.getAbodeId();//居住地住宅id
                Boolean inside2 = record.getInside2();//居住地区域内外标识，true是辖区内居住地

                if(StringUtils.hasText(abodeId) && inside2){
                    LambdaQueryWrapper<Residence> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(Residence::getId,abodeId);
                    lambdaQueryWrapper.eq(Residence::getEnabled,true);
                    Residence residence = residenceDao.selectOne(lambdaQueryWrapper);

                    LambdaQueryWrapper<SysCommunity> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(SysCommunity::getId,residence.getCommunityId());
                    wrapper.eq(SysCommunity::getEnable,true);
                    SysCommunity sysCommunity = sysCommunityDao.selectOne(wrapper);
                    StringBuilder stringBuilder = new StringBuilder();
                    if(StringUtils.hasText(sysCommunity.getName())){
                        stringBuilder.append(sysCommunity.getName());//社区名称
                    }
                    LambdaQueryWrapper<SysPlot> wrapper2 = new LambdaQueryWrapper<>();
                    wrapper2.eq(SysPlot::getId,residence.getPlotId());
                    wrapper2.eq(SysPlot::getEnabled,true);
                    SysPlot sysPlot = sysPlotDao.selectOne(wrapper2);
                    if(StringUtils.hasText(sysPlot.getName())){
                        stringBuilder.append(sysPlot.getName());//小区名称
                    }
                    //住宅地址
                    String address = residence.getAddress();
                    if(StringUtils.hasText(address)){
                        if(address.contains("/")){
                            String[] split = address.split("/");
                            stringBuilder.append(split[0]);//楼房楼栋
                            stringBuilder.append(split[1]);//楼房单元
                        }else {
                            stringBuilder.append(address);//平房/别墅
                        }
                    }
                    //门牌号
                    if(StringUtils.hasText(residence.getHouseNumber())){
                        stringBuilder.append(residence.getHouseNumber());
                    }
                    record.setAbode_address(stringBuilder.toString());
                }else {
                    StringBuilder stringBuilder = new StringBuilder();
                    //辖区外
                    String out2Province = record.getOut2Province();//省
                    if(StringUtils.hasText(out2Province)){
                        stringBuilder.append(out2Province);
                    }
                    String out2City = record.getOut2City();//市
                    if(StringUtils.hasText(out2City)){
                        stringBuilder.append(out2City);
                    }
                    String out2FullAddress = record.getOut2FullAddress();//辖区外居住详细地址
                    if(StringUtils.hasText(out2FullAddress)){
                        stringBuilder.append(out2FullAddress);
                    }
                    record.setAbode_address(stringBuilder.toString());
                }

                String placeId = record.getPlaceId();//户籍地住宅id
                Boolean inside1 = record.getInside1();//户籍地区域内外标识，true是辖区内户籍地
                if(StringUtils.hasText(placeId) && inside1){
                    LambdaQueryWrapper<Residence> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(Residence::getId,placeId);
                    lambdaQueryWrapper.eq(Residence::getEnabled,true);
                    Residence residence = residenceDao.selectOne(lambdaQueryWrapper);

                    LambdaQueryWrapper<SysCommunity> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(SysCommunity::getId,residence.getCommunityId());
                    wrapper.eq(SysCommunity::getEnable,true);
                    SysCommunity sysCommunity = sysCommunityDao.selectOne(wrapper);
                    StringBuilder stringBuilder = new StringBuilder();
                    if(StringUtils.hasText(sysCommunity.getName())){
                        stringBuilder.append(sysCommunity.getName());//社区名称
                    }
                    LambdaQueryWrapper<SysPlot> wrapper2 = new LambdaQueryWrapper<>();
                    wrapper2.eq(SysPlot::getId,residence.getPlotId());
                    wrapper2.eq(SysPlot::getEnabled,true);
                    SysPlot sysPlot = sysPlotDao.selectOne(wrapper2);
                    if(StringUtils.hasText(sysPlot.getName())){
                        stringBuilder.append(sysPlot.getName());//小区名称
                    }

                    //住宅地址
                    String address = residence.getAddress();
                    if(StringUtils.hasText(address)){
                        if(address.contains("/")){
                            String[] split = address.split("/");
                            stringBuilder.append(split[0]);//楼房楼栋
                            stringBuilder.append(split[1]);//楼房单元
                        }else {
                            stringBuilder.append(address);//平房/别墅
                        }
                    }
                    //门牌号
                    if(StringUtils.hasText(residence.getHouseNumber())){
                        stringBuilder.append(residence.getHouseNumber());
                    }
                    record.setPlace_address(stringBuilder.toString());
                }else {
                    StringBuilder stringBuilder = new StringBuilder();
                    //辖区外户籍地址
                    String out1Province = record.getOut1Province();//省
                    if(StringUtils.hasText(out1Province)){
                        stringBuilder.append(out1Province);
                    }
                    String out1City = record.getOut1City();//市
                    if(StringUtils.hasText(out1City)){
                        stringBuilder.append(out1City);
                    }
                    String out1FullAddress = record.getOut1FullAddress();//辖区外户籍详细地址
                    if(StringUtils.hasText(out1FullAddress)){
                        stringBuilder.append(out1FullAddress);
                    }
                    record.setPlace_address(stringBuilder.toString());
                }
            }
        }
        return ResponseResult.builder().data(page1).build();
    }

    /**
     * 新增住宅
     * @return
     */
    @Override
    @Transactional
    public ResponseResult save(ResidenceDto residenceDto, HttpServletRequest request) {
        List<String> addrArray = residenceDto.getAddrArray();
        String plotId = residenceDto.getPlotId();//获取小区id
        LambdaQueryWrapper<SysPlot> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysPlot::getId, plotId);
        wrapper.eq(SysPlot::getEnabled, true);
        SysPlot sysPlot = sysPlotDao.selectOne(wrapper);
        String bungalowVilla = sysPlot.getBungalowVilla();
        String buildingUnit = sysPlot.getBuildingUnit();
        //平房/别墅
        String id;
        String id2;
        if (addrArray.size() == 1) {
            //平房/别墅的区域id
            id = addrArray.get(0);
            PlotMessage plotMessage = JSON.parseObject(bungalowVilla, PlotMessage.class);
            List<BungalowVilla> bungalowVillas = plotMessage.getBungalowVillas();
            for (BungalowVilla villa : bungalowVillas) {
                if (id.equals(villa.getId())) {
                    residenceDto.setAddress(villa.getArea());
                    break;
                }
            }
        } else {
            //楼房和单元id
            id = addrArray.get(0);
            id2 = addrArray.get(1);
            PlotMessage plotMessage = JSON.parseObject(buildingUnit, PlotMessage.class);
            List<Building> buildings = plotMessage.getBuildings();
            for (Building building : buildings) {
                if (id.equals(building.getId())) {
                    StringBuilder address = new StringBuilder(building.getStoriedBuilding());
                    List<Unit> units = building.getUnits();
                    for (Unit unit : units) {
                        if (id2.equals(unit.getId())) {
                            address.append("/");
                            address.append(unit.getUnit());
                            residenceDto.setAddress(address.toString());
                            break;
                        }
                    }
                }
            }
        }
        String id3 = residenceDto.getId();
        //如果有id,代表修改
        if (StringUtils.hasText(id3)) {
            LambdaQueryWrapper<Residence> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Residence::getId, id3);
            lambdaQueryWrapper.eq(Residence::getEnabled, true);
            Residence residence1 = residenceDao.selectOne(lambdaQueryWrapper);

            LambdaQueryWrapper<Residence> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(Residence::getEnabled, true);
            lambdaQueryWrapper2.eq(Residence::getCommunityId, residenceDto.getCommunityId());
            lambdaQueryWrapper2.eq(Residence::getPlotId, residenceDto.getPlotId());
            lambdaQueryWrapper2.eq(Residence::getCategory, residenceDto.getCategory());

            lambdaQueryWrapper2.eq(Residence::getAddress, residenceDto.getAddress());
            lambdaQueryWrapper2.eq(Residence::getHouseNumber, residenceDto.getHouseNumber());
            Residence residence2 = residenceDao.selectOne(lambdaQueryWrapper2);

            if (Objects.isNull(residence2) || residence1.getId().equals(residence2.getId())) {
                LambdaQueryWrapper<Residence> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper3.eq(Residence::getId, residenceDto.getId());
                residenceDto.setUpdateTime(new Date());
                Residence residence = new Residence();
                BeanUtils.copyProperties(residenceDto, residence);
                int rows = residenceDao.update(residence, lambdaQueryWrapper3);
                return rows > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
            }
            return ResponseResult.builder().message("当前要修改的社区中的小区楼栋单元中房间号已经存在了，请更换之后再修改").code(ResultCode.SYSTEM_ERROR.getCode()).build();
        }
        //如果没有id,代表新增
        LambdaQueryWrapper<Residence> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(Residence::getEnabled, true);
        lambdaQueryWrapper2.eq(Residence::getCommunityId, residenceDto.getCommunityId());
        lambdaQueryWrapper2.eq(Residence::getPlotId, residenceDto.getPlotId());
        lambdaQueryWrapper2.eq(Residence::getCategory, residenceDto.getCategory());
        lambdaQueryWrapper2.eq(Residence::getAddress, residenceDto.getAddress());
        lambdaQueryWrapper2.eq(Residence::getHouseNumber, residenceDto.getHouseNumber());
        Residence residence2 = residenceDao.selectOne(lambdaQueryWrapper2);
        if (Objects.isNull(residence2)) {
            residenceDto.setCreateTime(new Date());
            residenceDto.setEnabled(true);
            Residence residence = new Residence();
            BeanUtils.copyProperties(residenceDto, residence);
            residence.setOwnerId(residenceDto.getOwnerId());//
            SysLog sysLog = new SysLog();
            sysLog.setIncident("住宅信息");
            sysLog.setType("新增");
            sysLog.setValue("业务日志");
            sysLog.setCreateTime(new Date());
            sysLog.setIp(GetIp.getIpAddr(request));
            User user2 = (User) ShiroUtils.getSubject().getPrincipal();
            sysLog.setOperator(user2.getUsername());
            StringBuilder stringBuilder = new StringBuilder();
            SysCommunity sysCommunity = sysCommunityDao.selectById(residence.getCommunityId());
            stringBuilder.append(sysCommunity.getName());
            SysPlot sysPlot1 = sysPlotDao.selectById(residence.getPlotId());
            stringBuilder.append(sysPlot1.getName()).append(residence.getAddress()).append("房间号:").append(residence.getHouseNumber());
            sysLog.setContent("房屋地址:"+stringBuilder);
            int rows = residenceDao.insert(residence);
            if(rows > 0){
                sysLog.setResult("成功");
            }else{
                sysLog.setResult("失败");
            }
            int insert = sysLogDao.insert(sysLog);
            if (insert > 0) {
                log.info("日志记录成功");
            } else {
                log.error("日志记录失败");
            }
            return rows > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
        }
        return ResponseResult.builder().message("当前要修改的社区中的小区楼栋单元中房间号已经存在了，请更换之后在添加").code(ResultCode.SYSTEM_ERROR.getCode()).build();
    }

    /**
     * 修改住宅
     * @return
     */
    @Override
    @Transactional
    public ResponseResult update(ResidenceDto residenceDto,HttpServletRequest request) {
        List<String> addrArray = residenceDto.getAddrArray();
        String plotId = residenceDto.getPlotId();//获取小区id
        LambdaQueryWrapper<SysPlot> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysPlot::getId, plotId);
        wrapper.eq(SysPlot::getEnabled, true);
        SysPlot sysPlot = sysPlotDao.selectOne(wrapper);
        String bungalowVilla = sysPlot.getBungalowVilla();
        String buildingUnit = sysPlot.getBuildingUnit();
        //平房/别墅
        String id;
        String id2;
        if (addrArray.size() == 1) {
            //平房/别墅的区域id
            id = addrArray.get(0);
            PlotMessage plotMessage = JSON.parseObject(bungalowVilla, PlotMessage.class);
            List<BungalowVilla> bungalowVillas = plotMessage.getBungalowVillas();
            for (BungalowVilla villa : bungalowVillas) {
                if (id.equals(villa.getId())) {
                    residenceDto.setAddress(villa.getArea());
                    break;
                }
            }
        } else {
            //楼房和单元id
            id = addrArray.get(0);
            id2 = addrArray.get(1);
            PlotMessage plotMessage = JSON.parseObject(buildingUnit, PlotMessage.class);
            List<Building> buildings = plotMessage.getBuildings();
            for (Building building : buildings) {
                if (id.equals(building.getId())) {
                    StringBuilder address = new StringBuilder(building.getStoriedBuilding());
                    List<Unit> units = building.getUnits();
                    for (Unit unit : units) {
                        if (id2.equals(unit.getId())) {
                            address.append("/");
                            address.append(unit.getUnit());
                            residenceDto.setAddress(address.toString());
                            break;
                        }
                    }
                }
            }
        }
        String id3 = residenceDto.getId();
        //如果有id,代表修改
        if (StringUtils.hasText(id3)) {
            LambdaQueryWrapper<Residence> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Residence::getId, id3);
            lambdaQueryWrapper.eq(Residence::getEnabled, true);
            Residence residence1 = residenceDao.selectOne(lambdaQueryWrapper);

            LambdaQueryWrapper<Residence> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(Residence::getEnabled, true);
            lambdaQueryWrapper2.eq(Residence::getCommunityId, residenceDto.getCommunityId());
            lambdaQueryWrapper2.eq(Residence::getPlotId, residenceDto.getPlotId());
            lambdaQueryWrapper2.eq(Residence::getCategory, residenceDto.getCategory());

            lambdaQueryWrapper2.eq(Residence::getAddress, residenceDto.getAddress());
            lambdaQueryWrapper2.eq(Residence::getHouseNumber, residenceDto.getHouseNumber());
            Residence residence2 = residenceDao.selectOne(lambdaQueryWrapper2);

            if (Objects.isNull(residence2) || residence1.getId().equals(residence2.getId())) {
                LambdaQueryWrapper<Residence> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper3.eq(Residence::getId, residenceDto.getId());
                residenceDto.setUpdateTime(new Date());
                Residence residence = new Residence();
                BeanUtils.copyProperties(residenceDto, residence);
                int rows = residenceDao.update(residence, lambdaQueryWrapper3);
                SysLog sysLog = new SysLog();
                sysLog.setIncident("住宅信息");
                sysLog.setType("修改");
                sysLog.setValue("业务日志");
                sysLog.setCreateTime(new Date());
                sysLog.setIp(GetIp.getIpAddr(request));
                User user2 = (User) ShiroUtils.getSubject().getPrincipal();
                sysLog.setOperator(user2.getUsername());
                StringBuilder stringBuilder = new StringBuilder();
                SysCommunity sysCommunity = sysCommunityDao.selectById(residence1.getCommunityId());
                stringBuilder.append(sysCommunity.getName());
                SysPlot sysPlot1 = sysPlotDao.selectById(residence1.getPlotId());
                stringBuilder.append(sysPlot1.getName()).append(residence1.getAddress()).append(residence1.getHouseNumber());
                sysLog.setContent("房屋地址:"+stringBuilder);
                if(rows > 0){
                    sysLog.setResult("成功");
                }else{
                    sysLog.setResult("失败");
                }
                StringBuilder stringBuilder1 = new StringBuilder();
                //跟新前
                if(!residence1.getClasses().equals(residence.getClasses())){
                    stringBuilder1.append("住宅类别被修改，修改前:").append(residence1.getClasses()).append(",修改后:").append(residence.getClasses()).append("。");
                }
                if(!residence1.getCategory().equals(residence.getCategory())){
                    stringBuilder1.append("房屋类型被修改，修改前:").append(residence1.getCategory()).append(",修改后:").append(residence.getCategory()).append("。");
                }
                if(!residence1.getCommunityId().equals(residence.getCommunityId())){
                    SysCommunity sysCommunity1 = sysCommunityDao.selectById(residence1.getCommunityId());
                    SysCommunity sysCommunity2 = sysCommunityDao.selectById(residence.getCommunityId());
                    stringBuilder1.append("所属社区被修改，修改前:").append(sysCommunity1.getName()).append(",修改后:").append(sysCommunity2.getName()).append("。");
                }
                if(!residence1.getPlotId().equals(residence.getPlotId())){
                    SysPlot sysPlot2 = sysPlotDao.selectById(residence1.getPlotId());
                    SysPlot sysPlot3 = sysPlotDao.selectById(residence.getPlotId());
                    stringBuilder1.append("所属小区被修改，修改前:").append(sysPlot2.getName()).append(",修改后:").append(sysPlot3.getName()).append("。");
                }
                if(!residence1.getAddress().equals(residence.getAddress())){
                    stringBuilder1.append("详细地址被修改，修改前:").append(residence1.getAddress()).append(",修改后:").append(residence.getAddress()).append("。");
                }
                if(!residence1.getHouseNumber().equals(residence.getHouseNumber())){
                    stringBuilder1.append("门牌号被修改，修改前:").append(residence1.getHouseNumber()).append(",修改后:").append(residence.getHouseNumber()).append("。");
                }
                //residence1:数据库总查询的
                //residence是新提交上来的数据
                if(StringUtils.hasText(residence1.getOwnerId())){
                    if(StringUtils.hasText(residence.getOwnerId())){
                        if(!residence1.getOwnerId().equals(residence.getOwnerId())){
                            Person person = personDao.selectById(residence1.getOwnerId());
                            Person person2 = personDao.selectById(residence.getOwnerId());
                            if(Objects.nonNull(person)){
                                if(Objects.nonNull(person2)){
                                    stringBuilder1.append("业主被修改，修改前:").append(person.getName()).append(",修改后:").append(person2.getName()).append("。");
                                }else {
                                    stringBuilder1.append("业主被修改，修改前:").append(person.getName()).append(",修改后:无").append("。");
                                }
                            }else {
                                if(Objects.nonNull(person2)){
                                    stringBuilder1.append("业主被修改，修改前:无").append(",修改后:无").append("。");
                                }
                            }
                        }
                    }else{
                        Person person = personDao.selectById(residence1.getOwnerId());
                        stringBuilder1.append("业主被修改，修改前:").append(person.getName()).append(",修改后:无").append("。");
                    }
                }else{
                    if(StringUtils.hasText(residence.getOwnerId())){
                        Person person2 = personDao.selectById(residence.getOwnerId());
                        stringBuilder1.append("业主被修改，修改前:无").append(",修改后:").append(person2.getName()).append("。");
                    }
                }
                //residence:要修改的数据
                //residence 修改前，数据库中查询的数据
                if(residence1.getRemark() != null){
                    if(StringUtils.hasText(residence.getRemark())){
                        if(!residence1.getRemark().equals(residence.getRemark())){
                            stringBuilder1.append("备注被修改，修改前:").append(residence1.getRemark()).append(",修改后:").append(residence.getRemark()).append("。");
                        }
                    }else {
                        stringBuilder1.append("备注被修改，修改前:").append(residence1.getRemark()).append(",修改后:无").append("。");
                    }
                }else {
                    if(StringUtils.hasText(residence.getRemark())){
                        stringBuilder1.append("备注被修改，修改前:无").append(",修改后:").append(residence.getRemark()).append("。");
                    }
                }
                sysLog.setDetails(stringBuilder1.toString());
                int insert = sysLogDao.insert(sysLog);
                if (insert > 0) {
                    log.info("日志记录成功");
                } else {
                    log.error("日志记录失败");
                }
                return rows > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
            }
            return ResponseResult.builder().message("当前要修改的社区中的小区楼栋单元中房间号已经存在了，请更换之后再修改").code(ResultCode.SYSTEM_ERROR.getCode()).build();
        }
        //如果没有id,代表新增
        LambdaQueryWrapper<Residence> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(Residence::getEnabled, true);
        lambdaQueryWrapper2.eq(Residence::getCommunityId, residenceDto.getCommunityId());
        lambdaQueryWrapper2.eq(Residence::getPlotId, residenceDto.getPlotId());
        lambdaQueryWrapper2.eq(Residence::getCategory, residenceDto.getCategory());
        lambdaQueryWrapper2.eq(Residence::getAddress, residenceDto.getAddress());
        lambdaQueryWrapper2.eq(Residence::getHouseNumber, residenceDto.getHouseNumber());
        Residence residence2 = residenceDao.selectOne(lambdaQueryWrapper2);
        if (Objects.isNull(residence2)) {
            residenceDto.setCreateTime(new Date());
            residenceDto.setEnabled(true);
            Residence residence = new Residence();
            BeanUtils.copyProperties(residenceDto, residence);
            residence.setOwnerId(residenceDto.getOwnerId());//
            int rows = residenceDao.insert(residence);
            return rows > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
        }
        return ResponseResult.builder().message("当前要修改的社区中的小区楼栋单元中房间号已经存在了，请更换之后在添加").code(ResultCode.SYSTEM_ERROR.getCode()).build();
    }

    /**
     * 根据id，删除(批量删除)住宅列表
     * @param ids
     * @return
     */
    @Override
    public ResponseResult delete(List<String> ids) {
        //当前住宅下面没有关联入住人员id和户籍人员id的时候，才可以删除
        for (String id : ids) {
            LambdaQueryWrapper<Person> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Person::getAbodeId,id);
            lambdaQueryWrapper.eq(Person::getEnabled,true);
            List<Person> people = personDao.selectList(lambdaQueryWrapper);
            if(people.size()>0){
                return ResponseResult.builder().message("当前住宅下，关联的有入住人员，不能删除").code(ResultCode.SYSTEM_ERROR.getCode()).build();
            }
            LambdaQueryWrapper<Person> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Person::getPlaceId,id);
            queryWrapper.eq(Person::getEnabled,true);
            List<Person> people1 = personDao.selectList(queryWrapper);
            if(people1.size()>0){
                return ResponseResult.builder().message("当前住宅下，关联的有户籍人员，不能删除").code(ResultCode.SYSTEM_ERROR.getCode()).build();
            }
        }
        int rows = residenceDao.updateEnabled(ids);
        return rows > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
    }

    /**
     * 查询住宅列表信息/或条件查询,并分页返回
     * @param pageQuery
     * @return
     */
    @Override
    public ResponseResult findListResidence(ResidencePageQuery pageQuery) {
        Integer page = pageQuery.getPage();
        Integer limit = pageQuery.getLimit();
        if(Objects.isNull(page) || Objects.isNull(limit)){
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("页码数和每页显得的天数不能为空").build();
        }
        //特殊处理详细地址
        String newDetailedAddress = null;
        ResidenceExcel residentia = pageQuery.getCondition();
        if(residentia != null && residentia.getDetailedAddress() != null){
            if(residentia.getDetailedAddress().size()>1){
                List<String> detailedAddress = residentia.getDetailedAddress();
                newDetailedAddress  =  detailedAddress.get(0) +"/"+ detailedAddress.get(1);
            }else{
                List<String> detailedAddress = residentia.getDetailedAddress();
                newDetailedAddress = detailedAddress.get(0);
            }
        }
        String keyWord = null;
        String residenceClasses = null;
        String residenceCategory = null;
        String communityId = null;
        String plotId = null;
        String detailedAddress = null;
        String houseNumber = null;
        assert residentia != null;
        keyWord = residentia.getKeyWord();//关键字
        residenceClasses = residentia.getResidenceClasses();//住宅类别
        residenceCategory = residentia.getResidenceCategory();//房屋类别
        communityId = residentia.getCommunityId();//社区id
        plotId = residentia.getPlotId();//小区id
        detailedAddress = newDetailedAddress;//详细地址
        houseNumber = residentia.getHouseNumber();//门牌号

        //获取当前登陆人的信息
        User user = (User) ShiroUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper5 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper5.eq(SysUserRole::getUserId, user.getId());
        SysUserRole sysUserRole = sysUserRoleDao.selectOne(lambdaQueryWrapper5);
        String roleKey = sysRoleDao.findByRoles(sysUserRole.getRoleId());
        //如果是街道管理员
        if ("street:admin".equals(roleKey)) {
            PageDTO<ResidenceDto> pageDTO = new PageDTO<>(page, limit);
            PageDTO<ResidenceDto> pageDTO1 = residenceDao.pageResidenceList(pageDTO, null, keyWord, residenceClasses, residenceCategory, communityId, plotId, detailedAddress, houseNumber);
            return ResponseResult.builder().data(pageDTO1).build();
        }
        //如果不是街道管理员
        List<String> commnityIds = sysUserCommunityDao.commnityIds(user.getId());
        if (Objects.isNull(commnityIds) || commnityIds.size() <= 0) {
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("当前用户还没有任何社区权限").build();
        }
        PageDTO<ResidenceDto> pageDTO = new PageDTO<>(page, limit);
        PageDTO<ResidenceDto> pageDTO1 = residenceDao.pageResidenceList(pageDTO, commnityIds, keyWord, residenceClasses, residenceCategory, communityId, plotId, detailedAddress, houseNumber);
        return ResponseResult.builder().data(pageDTO1).build();
    }

    /**
     * 双击查看社区列表中的详情信息
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findByCommunityId(String id) {
        ResidenceDto residenceDto = residenceDao.findByCommunityId(id);
        if (!Objects.isNull(residenceDto) && (residenceDto.getCategory() != null)) {
            String category = residenceDto.getCategory();
            LambdaQueryWrapper<SysPlot> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysPlot::getId, residenceDto.getPlotId());
            SysPlot sysPlot = sysPlotDao.selectOne(lambdaQueryWrapper);
            String address = residenceDto.getAddress();
            if (category.equals("平房/别墅")) {
                String bungalowVilla = sysPlot.getBungalowVilla();
                PlotMessage plotMessage = JSON.parseObject(bungalowVilla, PlotMessage.class);
                List<BungalowVilla> bungalowVillas = plotMessage.getBungalowVillas();
                List<String> addrArray = new LinkedList<>();
                for (BungalowVilla villa : bungalowVillas) {
                    if (villa.getArea().equals(address)) {
                        addrArray.add(villa.getId());
                        break;
                    }
                }
                residenceDto.setAddrArray(addrArray);
                return ResponseResult.builder().data(residenceDto).build();
            }
            String[] strings = address.split("/");
            String buildingUnit = sysPlot.getBuildingUnit();
            PlotMessage plotMessage = JSON.parseObject(buildingUnit, PlotMessage.class);
            List<Building> buildings = plotMessage.getBuildings();
            List<String> addrArray = new LinkedList<>();
            for (Building building : buildings) {
                if (building.getStoriedBuilding().equals(strings[0])) {
                    addrArray.add(building.getId());
                    List<Unit> units = building.getUnits();
                    for (Unit unit : units) {
                        if (unit.getUnit().equals(strings[1])) {
                            addrArray.add(unit.getId());
                            break;
                        }
                    }
                }
            }
            residenceDto.setAddrArray(addrArray);
            return ResponseResult.builder().data(residenceDto).build();
        }
        return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
    }

    /**
     * 批量添加楼房,平房/别墅
     *
     * @return
     */
    @Override
    public ResponseResult batchSave(ResidenceDto residenceDto,HttpServletRequest request) {
        List<String> addrArray1 = residenceDto.getAddrArray();
        if (Objects.isNull(addrArray1) || addrArray1.size() <= 0) {
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("未添加详细地址的小区不能批量添加").build();
        }
        Rules rules = residenceDto.getRules();
        String floor = rules.getFloor();//楼层1-20
        String room = rules.getRoom();//房间01-10
        //如果floor不为空，则代表当前添加的楼房
        if (StringUtils.hasText(floor)) {
            String[] floorNumber = floor.split("-");
            String startFloor = floorNumber[0].replaceFirst("^0*", "");
            String endFloor = floorNumber[1].replaceFirst("^0*", "");
            int startFloorNum = 0;
            int endFloorNum = 0;
            try {
                startFloorNum = Integer.parseInt(startFloor);
                endFloorNum = Integer.parseInt(endFloor);
            } catch (Exception exception) {
                log.info("楼房楼层号数字解析错误！");
            }

            String[] roomNumber = room.split("-");
            String startRoom = roomNumber[0].replaceFirst("^0*", "");
            String endRoom = roomNumber[1].replaceFirst("^0*", "");
            int startRoomrNum = 0;
            int endRoomrNum = 0;
            try {
                startRoomrNum = Integer.parseInt(startRoom);
                endRoomrNum = Integer.parseInt(endRoom);
            } catch (Exception exception) {
                log.info("楼房房间号数字解析错误！");
            }
            if (startFloorNum != 0 && endFloorNum != 0 && startRoomrNum != 0 && endRoomrNum != 0) {
                log.info("楼房房间号和楼层号解析成功！");
            } else {
                return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("房间号和楼层号输入得不正确").build();
            }
            if (startFloorNum > endFloorNum || startRoomrNum > endRoomrNum) {
                log.info("楼房房间号或楼层号输入错误");
                return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("房间号和楼层号输入不正确").build();
            }
            List<Residence> residenceList = new ArrayList<>();

            List<String> addrArray = residenceDto.getAddrArray();
            String buildingId = addrArray.get(0);//楼栋id
            String unitId = addrArray.get(1);//单元id
            LambdaQueryWrapper<SysPlot> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysPlot::getId, residenceDto.getPlotId());
            SysPlot sysPlot = sysPlotDao.selectOne(lambdaQueryWrapper);
            for (int i = startFloorNum; i <= endFloorNum; i++) {
                //处理门牌号
                StringBuilder houseNumber = new StringBuilder();
                houseNumber.append(rules.getPrefix());//前缀
                houseNumber.append(i);
                for (int j = startRoomrNum; j <= endRoomrNum; j++) {
                    StringBuilder houseNumber2 = new StringBuilder(houseNumber);
                    Residence residence = new Residence();
                    int length = roomNumber[1].length();
                    if (length > 1) {
                        houseNumber2.append("0");
                    }
                    houseNumber2.append(j);
                    houseNumber2.append(rules.getSuffix());
                    BeanUtils.copyProperties(residenceDto, residence);
                    residence.setEnabled(true);
                    residence.setCreateTime(new Date());
                    residence.setHouseNumber(houseNumber2.toString());
                    if ("楼房".equals(residenceDto.getCategory())) {
                        if (sysPlot != null && (StringUtils.hasText(sysPlot.getBuildingUnit()))) {
                            String buildingUnit = sysPlot.getBuildingUnit();
                            PlotMessage plotMessage = JSON.parseObject(buildingUnit, PlotMessage.class);
                            List<Building> buildings = plotMessage.getBuildings();
                            for (Building building : buildings) {
                                if (building.getId().equals(buildingId)) {
                                    StringBuilder address = new StringBuilder(building.getStoriedBuilding());
                                    List<Unit> units = building.getUnits();
                                    for (Unit unit : units) {
                                        if (unit.getId().equals(unitId)) {
                                            address.append("/").append(unit.getUnit());
                                            residence.setAddress(address.toString());
                                            residenceList.add(residence);
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            LambdaQueryWrapper<Residence> queryWrapper11 = new LambdaQueryWrapper<>();
            queryWrapper11.eq(Residence::getEnabled,true);
            List<Residence> residenceList1 = residenceDao.selectList(queryWrapper11);
            for (Residence residence : residenceList) {
                for (Residence residence1 : residenceList1) {
                    if (residence.getCategory().equals(residence1.getCategory()) && residence.getCommunityId().equals(residence1.getCommunityId()) && residence.getPlotId().equals(residence1.getPlotId()) && residence.getAddress().equals(residence1.getAddress()) && residence.getHouseNumber().equals(residence1.getHouseNumber())) {
                        log.info("批量插入时，出现重复的楼层单元和房间号");
                        return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("批量插入时，出现重复的楼层单元和房间号，请跟换之后，再插入！楼栋是:" + residence1.getAddress() + "房间号是:" + residence1.getHouseNumber()).data(ResultCode.SYSTEM_ERROR.getMessage()).build();
                    }
                }
            }
            log.info("开始插入楼房{}", residenceList);
            int i = 0;
            for (Residence residence : residenceList) {
                int r = residenceDao.insert(residence);
                if(r > 0){
                    i+=r;
                }
            }
            SysLog sysLog = new SysLog();
            sysLog.setIncident("住宅信息");
            sysLog.setType("批量添加");
            sysLog.setValue("业务日志");
            sysLog.setCreateTime(new Date());
            sysLog.setIp(GetIp.getIpAddr(request));
            User user2 = (User) ShiroUtils.getSubject().getPrincipal();
            sysLog.setOperator(user2.getUsername());
            sysLog.setContent("添加住宅:共"+residenceList.size()+"条");
            if(i > 0){
                sysLog.setResult("成功");
                StringBuilder stringBuilder = new StringBuilder();
                for (Residence residence : residenceList) {
                    SysCommunity sysCommunity = sysCommunityDao.selectById(residence.getCommunityId());
                    SysPlot sysPlot1 = sysPlotDao.selectById(residence.getPlotId());
                    stringBuilder.append("房屋地址:")
                            .append(sysCommunity.getName())
                            .append(sysPlot1.getName())
                            .append(residence.getAddress())
                            .append(residence.getHouseNumber());
                }
                sysLog.setDetails(stringBuilder.toString());
            }else{
                sysLog.setResult("失败");
            }
            int insert = sysLogDao.insert(sysLog);
            if (insert > 0) {
                log.info("日志记录成功");
            } else {
                log.error("日志记录失败");
            }
            return i > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
        }
        //否则当前添加的是平房/别墅
        String[] roomNumber = room.split("-");
        String startRoom = roomNumber[0].replaceFirst("^0*", "");
        String endRoom = roomNumber[1].replaceFirst("^0*", "");
        int startRoomrNum = 0;
        int endRoomrNum = 0;
        try {
            startRoomrNum = Integer.parseInt(startRoom);
            endRoomrNum = Integer.parseInt(endRoom);
        } catch (Exception exception) {
            log.info("平房/别墅房间号数字解析错误！");
        }
        if (startRoomrNum != 0 && endRoomrNum != 0) {
            log.info("平房/别墅房间号解析成功！");
        } else {
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("房间号和楼层号输入得不正确").build();
        }
        if (startRoomrNum > endRoomrNum) {
            log.info("楼房房间号或楼层号输入错误");
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("房间号和楼层号输入不正确").build();
        }
        List<Residence> residenceList = new ArrayList<>();

        List<String> addrArray = residenceDto.getAddrArray();
        String bungalowVillaId = addrArray.get(0);//平房/别墅id
        LambdaQueryWrapper<SysPlot> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysPlot::getId, residenceDto.getPlotId());
        SysPlot sysPlot = sysPlotDao.selectOne(lambdaQueryWrapper);
        for (int i = startRoomrNum; i <= endRoomrNum; i++) {
            //处理门牌号
            Residence residence = new Residence();
            BeanUtils.copyProperties(residenceDto, residence);
            residence.setEnabled(true);
            residence.setCreateTime(new Date());
            StringBuilder houseNumber = new StringBuilder();
            houseNumber.append(rules.getPrefix());//前缀
            int length = roomNumber[1].length();
            for (int i1 = 0; i1 < (length - 1); i1++) {
                houseNumber.append("0");//加几个0
            }
            houseNumber.append(i);//当前房号
            houseNumber.append(rules.getSuffix());//后缀
            residence.setHouseNumber(houseNumber.toString());
            if ("平房/别墅".equals(residenceDto.getCategory())) {
                if (sysPlot != null && (StringUtils.hasText(sysPlot.getBungalowVilla()))) {
                    String bungalowVilla = sysPlot.getBungalowVilla();
                    PlotMessage plotMessage = JSON.parseObject(bungalowVilla, PlotMessage.class);
                    List<BungalowVilla> bungalowVillas = plotMessage.getBungalowVillas();
                    for (BungalowVilla villa : bungalowVillas) {
                        if (villa.getId().equals(bungalowVillaId)) {
                            residence.setAddress(villa.getArea());
                            residenceList.add(residence);
                            break;
                        }
                    }
                }
            }
        }
        LambdaQueryWrapper<Residence> queryWrapper12 = new LambdaQueryWrapper<>();
        queryWrapper12.eq(Residence::getEnabled,true);
        List<Residence> residenceList1 = residenceDao.selectList(queryWrapper12);
        for (Residence residence : residenceList) {
            for (Residence residence1 : residenceList1) {
                if (residence.getCategory().equals(residence1.getCategory()) && residence.getCommunityId().equals(residence1.getCommunityId()) && residence.getPlotId().equals(residence1.getPlotId()) && residence.getAddress().equals(residence1.getAddress()) && residence.getHouseNumber().equals(residence1.getHouseNumber())) {
                    log.info("批量插入时，出现重复的社区下同小区的平房/别墅区域，请跟换之后，再插入！");
                    return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("当前批量插入平房/别墅已经重复了，重复的是平房/别墅的详细地址:" + residence1.getAddress() + ",区域是:" + residence1.getHouseNumber()).data(ResultCode.SYSTEM_ERROR.getMessage()).build();
                }
            }
        }
        log.info("开始插入平房/别墅{}", residenceList);
        int i = 0;
        for (Residence residence : residenceList) {
            int r = residenceDao.insert(residence);
            if(r > 0){
                i += r;
            }
        }
        SysLog sysLog = new SysLog();
        sysLog.setIncident("住宅信息");
        sysLog.setType("批量添加");
        sysLog.setValue("业务日志");
        sysLog.setCreateTime(new Date());
        sysLog.setIp(GetIp.getIpAddr(request));
        User user2 = (User) ShiroUtils.getSubject().getPrincipal();
        sysLog.setOperator(user2.getUsername());
        sysLog.setContent("添加住宅:共"+residenceList.size()+"条");
        if(i > 0){
            sysLog.setResult("成功");
            StringBuilder stringBuilder = new StringBuilder();
            for (Residence residence : residenceList) {
                SysCommunity sysCommunity = sysCommunityDao.selectById(residence.getCommunityId());
                SysPlot sysPlot1 = sysPlotDao.selectById(residence.getPlotId());
                stringBuilder.append("房屋地址:")
                        .append(sysCommunity.getName())
                        .append(sysPlot1.getName())
                        .append(residence.getAddress())
                        .append(residence.getHouseNumber());
            }
            sysLog.setDetails(stringBuilder.toString());
        }else{
            sysLog.setResult("失败");
        }
        int insert = sysLogDao.insert(sysLog);
        if (insert > 0) {
            log.info("日志记录成功");
        } else {
            log.error("日志记录失败");
        }
        return i > 0 ? ResponseResult.builder().build() : ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message(ResultCode.SYSTEM_ERROR.getMessage()).build();
    }

    /**
     * 导出选中的住宅列表
     *
     * @param residenceExcel
     * @return
     */
    @Override
    public ResponseResult residentialExcel(ResidenceExcel residenceExcel) {
        //创建一个目录
        File dir = new File(basePath);
        if(!dir.exists()){
            //目录如果不存在就创建一个
            dir.mkdirs();
        }

        //特殊处理详细地址
        String newDetailedAddress = null;
        if(residenceExcel != null && residenceExcel.getDetailedAddress() != null){
            if(residenceExcel.getDetailedAddress().size()>1){
                List<String> detailedAddress = residenceExcel.getDetailedAddress();
                newDetailedAddress  =  detailedAddress.get(0) +"/"+ detailedAddress.get(1);
            }else{
                List<String> detailedAddress = residenceExcel.getDetailedAddress();
                newDetailedAddress = detailedAddress.get(0);
            }
        }
        //导出全部的/条件刷选的
        String keyWord = null;
        String residenceClasses = null;
        String residenceCategory = null;
        String communityId = null;
        String plotId = null;
        String detailedAddress = null;
        String houseNumber = null;
        List<String> ids = null;
        assert residenceExcel != null;
        ids = residenceExcel.getIds();
        keyWord = residenceExcel.getKeyWord();//关键字
        residenceClasses = residenceExcel.getResidenceClasses();//住宅类别
        residenceCategory = residenceExcel.getResidenceCategory();//房屋类别
        communityId = residenceExcel.getCommunityId();//社区id
        plotId = residenceExcel.getPlotId();//小区id
        detailedAddress = newDetailedAddress;//详细地址
        houseNumber = residenceExcel.getHouseNumber();//门牌号

        //获取当前登陆人的信息
        User user = (User) ShiroUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper5 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper5.eq(SysUserRole::getUserId, user.getId());
        SysUserRole sysUserRole = sysUserRoleDao.selectOne(lambdaQueryWrapper5);
        String roleKey = sysRoleDao.findByRoles(sysUserRole.getRoleId());
        List<ResidenceExcel> conditionExcel = null;
        if ("street:admin".equals(roleKey)) {
            conditionExcel = residenceDao.findConditionExcel(ids,null, keyWord, residenceClasses, residenceCategory, communityId, plotId, detailedAddress, houseNumber);
        }else{
            List<String> commnityIds = sysUserCommunityDao.commnityIds(user.getId());
            if (Objects.isNull(commnityIds) || commnityIds.size() <= 0) {
                return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("当前用户还没有任何社区权限").build();
            }
            conditionExcel = residenceDao.findConditionExcel(ids,commnityIds, keyWord, residenceClasses, residenceCategory, communityId, plotId, detailedAddress, houseNumber);
        }
        try {
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
            String format = simpleDateFormat.format(date);
            String filePathName = basePath + format + "住宅.xlsx";
            EasyExcel.write(filePathName, ResidenceExcel.class).sheet("住宅信息").doWrite(conditionExcel);
            return ResponseResult.builder().data(filePathName).build();
        } catch (Exception ex) {
            log.info("写住宅列表excel时出现异常！");
            log.info(ex.getMessage());
            return ResponseResult.builder().code(ResultCode.SYSTEM_ERROR.getCode()).message("系统读写文件时，出现异常").build();
        }
    }
}
